package com.example.administrator.show.mian;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.util.SparseArray;
import android.view.View;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.Toast;

import com.example.administrator.show.HomeChildFragment;
import com.example.administrator.show.R;
import com.example.administrator.show.RootActivity;
import com.example.administrator.show.data.ImageList;
import com.example.administrator.show.home.HomeFragment;
import com.example.administrator.show.imagepicker.ImagePicker;
import com.example.administrator.show.imagepicker.bean.ImageItem;
import com.example.administrator.show.imagepicker.loader.GlideImageLoader;
import com.example.administrator.show.imagepicker.ui.ImageGridActivity;
import com.example.administrator.show.photo.PhotoFragment;
import com.example.administrator.show.photo.ShareFragment;
import com.example.administrator.show.photo.WebviewFragment;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.ArrayList;


/**
 * @author yexiuliang
 * @page
 * @data 2016-11-13
 */

public class MainActivity extends RootActivity implements View.OnClickListener ,PhotoFragment.titleSelectInterface,HomeFragment.homeFraInterface{


    private static final String SAVE_CURRENT_PAGE = "SAVE_CURRENT_PAGE";
    private static final int REQUEST_CODE_SELECT = 1000;

    public static final int TAKE_PHOTO = 2;

    private Page mCurrentPage;
    private Fragment mCurrentFragment;
    private WebView objwv;
    private static final int MY_PERMISSIONS_REQUEST_CALL_CAMERA = 1;

    private File mPictureFile;
    private ImageView back_img;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


      setContentView(R.layout.activity_main);


      //  FragmentManager manager = getSupportFragmentManager();
      //  HomeFragment   homeFragment=   (HomeFragment) manager.findFragmentById(R.id.fragment_container );
        ///objwv =  (WebView) homeFragment.getView().findViewById(R.id.wv);
      //  homeFragment.seturl();

    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt(SAVE_CURRENT_PAGE, mCurrentPage.ordinal());
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        if (savedInstanceState != null) {
            Page page = Page.values()[savedInstanceState.getInt(SAVE_CURRENT_PAGE)];

            FragmentManager fragmentManager = getSupportFragmentManager();
            FragmentTransaction transaction = fragmentManager.beginTransaction();

            //隐藏所有旧有的Fragment，使其重新初始化
            for (Page oldPage : Page.values()) {
                if (oldPage == page) {
                    continue;
                }
                Fragment f = fragmentManager.findFragmentByTag(getPageFragmentTag(oldPage));
                if (f != null) {
                    transaction.hide(f);
                }
            }
            transaction.commitAllowingStateLoss();
            fragmentManager.executePendingTransactions();

            selectPage(page);
        } else {
            selectPage(Page.HOME);
        }
    }

    @Override
    protected void onFindViews() {
        super.onFindViews();
        initImagePicker();
        View collectBtn = findViewById(R.id.home);
        View findBtn = findViewById(R.id.photo);
        View mineBtn = findViewById(R.id.me);
       back_img = (ImageView) findViewById(R.id.title_left_img);

        collectBtn.setOnClickListener(this);
        findBtn.setOnClickListener(this);
        mineBtn.setOnClickListener(this);
        back_img.setOnClickListener(this);



        //先初始化一遍,防止第二个fragment还未初始化,打开相册选择图片返回接收不到
        selectPage(Page.PHOTO);
        selectPage(Page.HOME);


        /*初始化webview*/


       // objwv.loadUrl("http://guocui.vqo.cn/Admin/index.php/Wap/index");


//        WebSettings settings = objwv.getSettings();
        //settings.setUseWideViewPort(true);
        ///settings.setLoadWithOverviewMode(true);
        ///    settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
       /* objwv.setWebViewClient(new WebViewClient(){

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String request) {

                objwv.loadUrl(request);
                return super.shouldOverrideUrlLoading(view, request);
            }
        });
*/

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            //添加图片返回
            if (data != null && requestCode == REQUEST_CODE_SELECT) {
                ArrayList<ImageItem> images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                if (images != null && images.size() > 0) {
                    Log.e("images", images.toString());
                    selectPage(Page.PHOTO);
                    EventBus.getDefault().post(new ImageList(images, true));
//                    Intent intent = new Intent(MainActivity.this, PhotoActivity.class);
//                    intent.putExtra(ImagePicker.EXTRA_RESULT_ITEMS, images);
//                    startActivity(intent);
                }
            }
        }



        if (resultCode == Activity.RESULT_OK) {
            String sdStatus = Environment.getExternalStorageState();
            if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) { // 检测sd是否可用
                Log.i("TestFile", "SD card is not avaiable/writeable right now.");
                return;
            }
           Bundle bundle = data.getExtras();
           // Bitmap Bitmap = data.getParcelableExtra("data");
            Bitmap bitmap = (Bitmap) bundle.get("data");// 获取相机返回的数据，并转换为Bitmap图片格式


            selectPage(Page.PHOTO);
            Bitmap curBitmap = bitmap;
            EventBus.getDefault().post(curBitmap);
        }
    }

    private void initImagePicker() {
        ImagePicker imagePicker = ImagePicker.getInstance();
        imagePicker.setImageLoader(new GlideImageLoader());   //设置图片加载器
        imagePicker.setSelectLimit(1);              //选中数量限制

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.me:
                ImagePicker.getInstance().setSelectLimit(1);
                Intent intent = new Intent(this, ImageGridActivity.class);
                startActivityForResult(intent, REQUEST_CODE_SELECT);
                break;
            case R.id.photo:
                paizhao();
             /*返回 按钮 */
            case R.id.title_left_img:
                HomeFragment homef = (HomeFragment)  mCurrentFragment.getFragmentManager().findFragmentById(R.id.fragment_container);
                homef.goback();
            default:
                Page page = Page.BUTTON_ID_MAP.get(view.getId());
                selectPage(page);
                break;
        }
    }
    public void paizhao(){

       /// ivHeadwearToPhoto.setVisibility(View.GONE);
        String state = Environment.getExternalStorageState(); //拿到sdcard是否可用的状态码
        if (state.equals(Environment.MEDIA_MOUNTED)) {   //如果可用

            if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                //如果没有授权，则请求授权
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, MY_PERMISSIONS_REQUEST_CALL_CAMERA);

              /// callCamera();
            } else {
                //有授权，直接开启摄像头
                callCamera();
            }

        } else {
            Toast.makeText(this, "sdcard不可用", Toast.LENGTH_SHORT).show();
        }

    }
/*请求相机的返回动作*/
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
       /// doNext(requestCode,grantResults);

        if (requestCode == MY_PERMISSIONS_REQUEST_CALL_CAMERA) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                callCamera();
            }


        }
    }





    public  void bt_person (){
       Log.v("bt_person","可以点击");
       selectPage(Page.HOME);

    }
    private void callCamera() {
        //启动相机
         Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");


        // 设置相机拍照后照片保存路径
        mPictureFile = new File(Environment.getExternalStorageDirectory(),
                "picture" + System.currentTimeMillis()/1000 + ".jpg");


    ///    intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
     //   intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(mPictureFile));
     //   intent.putExtra(MediaStore.Images.Media.ORIENTATION, 0);

        startActivityForResult(intent, TAKE_PHOTO);
    }

    public void selectPage(Page page) {
        if (page == null || mCurrentPage == page) {
            return;
        }
        String tag = getPageFragmentTag(page);
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction curTransaction = fragmentManager.beginTransaction();

        if (mCurrentPage != null) {
            View button = findViewById(mCurrentPage.buttonId);
            button.setSelected(false);
        }
        if (mCurrentFragment != null) {
            curTransaction.hide(mCurrentFragment);
           /// curTransaction.remove(mCurrentFragment);
        }

        Fragment   webfragment = Fragment.instantiate(this, Page.Webview.fragmentClass.getName());
        try {
            curTransaction.remove(webfragment);
        } catch (Exception e) {
           /// throw new ClassCastException(activity.toString() + "must implement  ");
        }

        //curTransaction.remove(fragment);
       fragmentManager.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);


        //隐藏所有旧有的Fragment，使其重新初始化
        for (Page oldPage : Page.values()) {
        if (oldPage == page) {
                continue;
            }
            Fragment f = fragmentManager.findFragmentByTag(getPageFragmentTag(oldPage));
            if (f != null) {
                curTransaction.hide(f);
            }
        }

      ///  fragmentManager.findFragmentByTag(getPageFragmentTag("WebviewFragment"));



        Fragment fragment = fragmentManager.findFragmentByTag(tag);
     //   if (fragment != null) {
      //      curTransaction.show(fragment);
       // } else {
            fragment = Fragment.instantiate(this, page.fragmentClass.getName());
            curTransaction.add(R.id.fragment_container, fragment, tag);
        ///curTransaction.hide();
       // }
        curTransaction.commitAllowingStateLoss();
        fragmentManager.executePendingTransactions();

        View button = findViewById(page.buttonId);
        button.setSelected(true);
        mCurrentPage = page;
        mCurrentFragment = fragment;
    }

    private String getPageFragmentTag(Page page) {
        return page.fragmentClass.getName();
    }

    @Override
    public void setweburl(String url) {

        selectPage(Page.Webview);

        WebviewFragment fragment2 = (WebviewFragment)  mCurrentFragment.getFragmentManager().findFragmentById(R.id.fragment_container);
        fragment2.seturl(url);


    }

    @Override
    public void goshare(Uri save_img_uri ,Bitmap tmp) {

        selectPage(Page.SHARE);
        ShareFragment shareF = (ShareFragment)  mCurrentFragment.getFragmentManager().findFragmentById(R.id.fragment_container);
        shareF.setImgUrl(save_img_uri,tmp);
    }

    @Override
    public void changeNav() {
       // WebviewFragment fragment2 = (WebviewFragment)  mCurrentFragment.getFragmentManager().findFragmentById(R.id.fragment_container);
       // fragment2.seturl(url);
       //导航改变
      //  ImageView  left_img = (ImageView) findViewById(R.id.title_left_img);
        back_img.setVisibility(View.VISIBLE);

        //left_img.setIM
        //buttonback3x
    }

    public enum Page {
        /**
         * 首页
         */
        HOME(R.id.home, HomeFragment.class),
        /**
         *
         */
        PHOTO(R.id.photo, PhotoFragment.class),

         Webview(R.id.photo, WebviewFragment.class),
        SHARE(R.id.photo, ShareFragment.class);


        public static final SparseArray<Page> BUTTON_ID_MAP = new SparseArray<Page>();

        /**
         * 关联的button id
         */
        public final int buttonId;
        /**
         * Fragment类
         */
        public final Class<? extends HomeChildFragment> fragmentClass;

        static {
            for (Page page : Page.values()) {
                BUTTON_ID_MAP.put(page.buttonId, page);
            }
        }

        private Page(int vbuttonId, Class<? extends HomeChildFragment> cls) {
            buttonId = vbuttonId;
            fragmentClass = cls;
        }
    }


/*
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode == KeyEvent.KEYCODE_BACK ){

            if(objwv!=null &&objwv.canGoBack()){

                objwv.goBack();

            }else{
                //  finish();

            }
            return  true;
        }


        return super.onKeyDown(keyCode, event);
    }
   */
}
